from django.shortcuts import render
from django.http import JsonResponse
from system.models import Role,Menu
from django.core.paginator import Paginator
from django.db.models import Q
from cmdb.settings import default_page,default_limit
from django.contrib.auth.decorators import login_required
from utils.findButtonPer import findButtonPermission
def role_page(request):
    # 这里进行判断权限部分
    role_obj = request.user.role.first()
    result = findButtonPermission(role_obj=role_obj,key='role')
    return render(request, 'system/role/role.html',result)

def roleAdd_page(request):
    return render(request, 'system/role/insert.html')

def roleEdit_page(request):
    return render(request, 'system/role/edit.html')

@login_required()
def getRoleData(request):
    try:
        role_list = Role.objects.all()
        role_count = Role.objects.count()
        list_role=[]
    except Exception as e:
        return JsonResponse({'code': 4000, 'msg': '查询数据失败！'})
    for i in role_list:
        dict = {}
        dict['id'] = i.id
        dict['key'] = i.key
        dict['sort'] = i.sort
        dict['name'] = i.name 
        dict['admin'] = i.admin 
        dict['data_range'] = i.data_range
        dict['description'] = i.description
        list_role.append(dict)
    pageIndex = request.GET.get('page')  # pageIndex = request.POST.get('pageIndex')
    pageSize = request.GET.get('limit')  # pageSize = request.POST.get('pageSize')
    if pageIndex is None:
        pageIndex = default_page
    if pageSize is None:
        pageSize = default_limit
    pageInator = Paginator(list_role, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []
    for contact in contacts:
        res.append(contact)
    Result = {'code': 0, 'msg': '成功！','count':role_count, 'data': res}
    return JsonResponse(Result)

@login_required()
def addRoleData(request):
    get_key = request.POST.get('key')
    get_name = request.POST.get('name')
    # 这里前端获取下拉框的时候，传上来默认就是名字就叫select,这里对应的是菜单权限
    get_menu = request.POST.get('select')
    get_sort = request.POST.get('sort')
    get_admin = request.POST.get('admin')
    get_data_range = request.POST.get('data_range')
    get_description = request.POST.get('description')
    menus = str(get_menu).split(',')
    menu_list = Menu.objects.values_list('id',flat=True)
    list_menu = []
    for i in menus:
        list_menu.append(int(i))
    try:
        if get_admin == 1: # 这里判断是否是admin
            obj = Role.objects.create(key=get_key,name=get_name,sort=get_sort,admin=get_admin,data_range=3,
            description=get_description,creator_id=request.user.id,dept_belong_id=request.user.dept.id)
            #这里多对多的情况下。
            menu_obj = Menu.objects.filter()
            obj.menu.add(*menu_obj)
            obj.save()
        else:
            obj = Role.objects.create(key=get_key,name=get_name,sort=get_sort,admin=get_admin,data_range=get_data_range,
            description=get_description,creator_id=request.user.id,dept_belong_id=request.user.dept.id)
            #这里多对多的情况下。
            menu_obj = Menu.objects.filter(id__in=list_menu)
            obj.menu.add(*menu_obj)
            obj.save()
    except Exception as e:
        return JsonResponse({'code': 4002, 'msg': '创建新的菜单失败，请联系管理员！'})
    Result = {'code': 0, 'msg': '创建新的菜单成功'}
    return JsonResponse(Result)

@login_required()
def editRoleData(request,id):
    key = request.POST.get('key')
    name = request.POST.get('name')
    menu = request.POST.get('select') #这里前段插件不知道为什么自动命名为select，应该是可以改的
    admin = request.POST.get('admin')
    print(admin)
    sort = request.POST.get('sort')
    data_range = request.POST.get('data_range')
    description = request.POST.get('description')
    menus = str(menu).split(",")
    list_menu = []
    for i in menus:
        list_menu.append(int(i))
    try:
        if int(admin) == 1: # 这里判断是否是admin
            obj = Role.objects.get(pk=id)
            obj.key=key
            obj.name=name
            obj.admin=int(1)
            obj.sort=sort
            obj.data_range=int(3)
            obj.description=description
            obj.menu.clear()
            obj.modifier=request.user.id
            menu_obj = Menu.objects.filter()
            obj.menu.add(*menu_obj) # 结构对象
            obj.save()
        else:
            obj = Role.objects.get(pk=id)
            obj.key=key
            obj.name=name
            obj.admin=admin
            obj.sort=sort
            obj.data_range=data_range
            obj.description=description
            obj.menu.clear()
            obj.modifier=request.user.id
            menu_obj = Menu.objects.filter(id__in=list_menu)
            obj.menu.add(*menu_obj) # 结构对象
            obj.save()
    except Exception as e:
        print(e)
        return JsonResponse({'code': 4002, 'msg': '修改新的菜单失败，请检查key值得唯一性！'})
    Result = {'code': 0, 'msg': '修改菜单成功'}
    return JsonResponse(Result)

@login_required()
def delRoleData(request,id):
    try:
        role_obj = Role.objects.get(pk=id)
    except Exception as e:
        return JsonResponse({'code': 202, 'msg': '未找到删除对象！'})
    try:
        role_obj.delete()
    except Exception as e:
        return JsonResponse({'code': 202, 'msg': '删除对象失败！'})
    return JsonResponse({'code': 0, 'msg':'删除成功！'})

@login_required()
def queryRoleData(request):
    name = request.GET.get('searchName')
    try:
        if len(name)==0:
            role_list = Role.objects.filter()
        else:
            role_list = Role.objects.filter(Q(key__contains=name)|Q(name__contains=name))
        count = len(list(role_list))
    except Exception as e:
        return JsonResponse({'code': 201, 'msg': 'role单查模块出现问题，请联系管理员！'})
    list1 = []
    for i in role_list:
        menu_id = i.menu.filter().values_list('id', flat=True)
        menus = list(menu_id)
        dict = {}
        dict['id'] = i.id
        dict['key'] = i.key
        dict['sort'] = i.sort
        dict['name'] = i.name 
        dict['menus'] = menus
        dict['admin'] = i.admin 
        dict['data_range'] = i.data_range
        dict['description'] = i.description
        list1.append(dict)
    pageIndex = request.GET.get('page')  # pageIndex = request.POST.get('pageIndex')
    pageSize = request.GET.get('limit')  # pageSize = request.POST.get('pageSize')
    pageInator = Paginator(list1, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []
    for contact in contacts:
        res.append(contact)
    return JsonResponse({'code': 0, 'msg': '成功！', 'count': count, 'data': res})